package api

import (
	"fmt"
	"net/http"
	"strconv"

	"gitee.com/h2ob/base"
	"gitee.com/h2ob/facada"
	"gitee.com/h2ob/infra"
	"github.com/gin-gonic/gin"
)

// @Summary(test)
func h2oHello(c *gin.Context) {
	c.String(http.StatusOK, "OK")
}

// @Summary(微信用户登录)
// @Accept  json
// @Produce json
// @Param `H2oWxLogin`
// @Response `H2oRsp`
// @Router /user/wxlogin [post]
func h2oWxLogin(c *gin.Context) {
	wxUsr := &facada.H2oWxLogin{}
	if err := c.BindJSON(wxUsr); err != nil {
		base.GLogger.Infoln("Can not find args")
		c.String(http.StatusBadRequest, "Can not find args")
		return
	}
	base.GLogger.Infof("start ......")
	rsp, err := infra.VerifyCode(wxUsr.WxCode)
	if err != nil {
		base.GLogger.Infoln("Unauthorized")
		c.String(http.StatusUnauthorized, "Unauthorized")
		return
	}
	openId := rsp.Openid
	base.GLogger.Infof("openid:%s", openId)
	user, err := infra.FindByOpenId(openId, facada.OID_WX)
	action := "Login"
	if err == nil {
		base.GLogger.Infof("Find uid:%d", user.Uid)
	} else {
		user, err = infra.AddNewUser(wxUsr.Nickname, openId, facada.OID_WX, wxUsr.Avatar)
		if err != nil {
			c.String(http.StatusInternalServerError, "Internal error")
			return
		}
		base.GLogger.Infof("Add:uid=%d", user.Uid)
		action = "Register"
	}
	role := base.H2O_USER_NORMAL
	if openId == base.GConf.Http.Admin {
		role = base.H2O_USER_ADMIN
		base.GLogger.Infof("uid=%d is %s", user.Uid, role)
	}
	uid := strconv.FormatUint(user.Uid, 10)
	jwt, err := base.GetToken(user.Nickname, uid, role)
	if err != nil {
		base.GLogger.Warnf("jwt failed:%s", err.Error())
		c.String(http.StatusInternalServerError, "Internal error")
	}
	c.Header("Authorization", fmt.Sprintf("Bearer %s", jwt))
	c.Header("XH2oRole", role)
	c.Header("XH2oAction", action)
	base.GLogger.Infof("over ......")
}

func h2oWxUploadAvator(c *gin.Context) {
	uid := c.MustGet(base.HEAD_USER_ID)
	//
	file, err := c.FormFile("file")
	if err != nil {
		base.GLogger.Info("Can not find file")
		c.String(http.StatusBadRequest, "Can not find file")
		return
	}
	img, err := file.Open()
	if err != nil {
		base.GLogger.Info("File open failed:%s", err.Error())
		c.String(http.StatusInternalServerError, "File error")
		return
	}
	dest := fmt.Sprintf("../upload/avator/%s%s", uid, infra.GetFileType(file.Filename))
	err = infra.FileCopy(img, dest)
	if err != nil {
		base.GLogger.Info("File Save failed:%s", err.Error())
	}
	img.Close()
	c.String(http.StatusOK, "OK")
}
